package com.java.user.controller;

import com.java.param.UserCheckParam;
import com.java.param.UserLoginParam;
import com.java.pojo.User;
import com.java.user.service.UserService;
import com.java.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 检查账号是否可以用
     * @param userCheckParam 接收检查的账号实体，内部有参数的检验注解
     * @param result 获取检验及外国的实体对象
     * @return 返回封装结果 R对象
     * @RequestBody 将前端的json数据转换成对象
     * @Validated 使检验配置生效，使NotBlank注解生效
     * BindingResult 必须紧跟检验对象，获取是否符合注解规则，符合 false,不符合 true
     */
    @PostMapping("/check")
    public R check(@RequestBody @Validated UserCheckParam userCheckParam, BindingResult result){

        boolean b = result.hasErrors();
        if(b){
            return R.fail("账号为空，不可使用！");
        }
        return userService.check(userCheckParam);
    }

    /**
     * 用户注册
     * @param user 用户信息
     * @param result 检验结果
     * @return 最终结果信息，Ok,error
     */
    @PostMapping("register")
    public R register(@RequestBody @Validated User user, BindingResult result){
        if(result.hasErrors()){
            return R.fail("参数异常，注册失败！");
        }
        return userService.register(user);
    }

    /**
     * 登录业务
     * @param userLoginParam
     * @param result
     * @return
     */

    @PostMapping("login")
    public R login(@RequestBody @Validated UserLoginParam userLoginParam,BindingResult result){
        if(result.hasErrors()){
            return R.fail("参数异常，登陆失败！");
        }
        return userService.login(userLoginParam);
    }
}
